package com.qys.livesMall.app.user.controller.sys;


import com.qys.livesMall.app.user.model.dto.sys.ChangeUserBalanceDTO;
import com.qys.livesMall.app.user.model.vo.PlatformBalanceVO;
import com.qys.livesMall.app.user.model.vo.UserBalanceVO;
import com.qys.livesMall.app.user.service.IH2AppUserBalanceService;
import com.qys.livesMall.common.result.R;
import com.qys.livesMall.finance.enums.AccountBusinessTypeEnum;
import com.qys.livesMall.finance.model.dto.AccountSearch;
import com.qys.livesMall.finance.model.dto.FinancePayDTO;
import com.qys.livesMall.finance.service.FinanceBusinessService;
import com.qys.livesMall.finance.util.BusinessNoUtil;
import com.qys.livesMall.framework.view.QysPage;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;

/**
 * 用户(平台)资金表 前端控制器
 * </p>
 *
 * @author dp
 * @since 2023-04-24
 */
@RestController
@RequestMapping("/sys/app/user/balance")
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
@Tag(name = "app-用户资金表")
public class SysH2AppUserBalanceController {

    private final IH2AppUserBalanceService userBalanceService;
    private final FinanceBusinessService financeBusinessService;

    /**
     * 用户资金列表
     * @param search
     * @return
     */
    @PostMapping("/page")
    @Operation(summary = "分页查询用户余额信息")
    public R<QysPage<UserBalanceVO>> page(@RequestBody AccountSearch search) {
        return R.ok(userBalanceService.page(search));
    }

    /**
     * 平台资金列表
     * @param search
     * @return
     */
    @PostMapping("/platformPage")
    @Operation(summary = "平台资金列表")
    public R<QysPage<PlatformBalanceVO>> platformPage(@RequestBody AccountSearch search) {
        return R.ok(userBalanceService.platformPage(search));
    }


    @PostMapping("/change/balance")
    @Operation(summary = "修改用户余额")
    public R<?> changeUserBalance(@RequestBody @Validated ChangeUserBalanceDTO dto) {

        //业务类型（赠送/扣减）
        AccountBusinessTypeEnum businessType = dto.getChangeAmount().compareTo(BigDecimal.ZERO) >= 0 ? AccountBusinessTypeEnum.GIFT : AccountBusinessTypeEnum.DEDUCT;

        FinancePayDTO financePayDTO = new FinancePayDTO();
        financePayDTO.setUserId(dto.getUserId());
        financePayDTO.setBusinessType(businessType);
        financePayDTO.setAmountIncurred(dto.getChangeAmount().abs());
        financePayDTO.setBusinessNo(BusinessNoUtil.get(businessType));
        financePayDTO.setDescription(dto.getRemark());
        financeBusinessService.pay(financePayDTO);

        if(!financePayDTO.getSuccess()){
            return R.fail(financePayDTO.getMessage());
        }

        return R.ok();
    }

}
